package dataStructDui;


import java.util.Arrays;

public class TestHeap {

    public int[] elem;
    public int usedSize;

    public TestHeap(){
        this.elem = new int[10];
    }

    public void initElem(int[] array){
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }

    private void shiftDown(int parent,int len){
        int child = 2*parent + 1;
        while (child < len){
            //  判断是否有左孩子
            if( child + 1 < len && elem[child] < elem[child + 1]){
                child++;
            }
            //  比较孩子与父亲结点 谁大
            if( elem[child] > elem[parent] ){
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                // 结点还要继续往下面的结点比较
                parent = child;
                child = 2*parent + 1;
            }else {
                break;
            }

        }

    }

    public void createHeap(){

        for (int parent = (usedSize-1-1)/2; parent >= 0 ; parent--) {
            shiftDown(parent,usedSize);
        }
        
    }


    //  向上调整建堆的时间复杂度为 N*logN
    //  堆添加一个元素
    public void offer(int val){
        //  判断是否会溢出
        if(isFul()){
            // 扩容
            elem = Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize++] = val;
        // 向上调整
        shiftUp(usedSize-1);
    }
    public boolean isFul(){
        return usedSize == elem.length;
    }
    //  向上调整
    public void shiftUp(int child){
        int parent = (child-1)/2;
        while (child > 0){
            if(elem[child] > elem[parent]) {
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                child = parent;
                parent = (child - 1) / 2;
            }else {
                break;
            }
        }

    }

    // 堆删除一个元素
    public void pop(){
        if (ifEmpty()){
            return;
        }
        int tmp = elem[0];
        elem[0] = elem[usedSize-1];
        elem[usedSize-1] = tmp;
        usedSize--;
        shiftDown(0,usedSize);

    }
    public boolean ifEmpty(){
        return usedSize == 0;
    }







}
